package com.haixiaoke.saas.manage.org.controller;

import java.util.List;
import java.util.Objects;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.org.domain.Dept;
import com.haixiaoke.saas.org.domain.DeptTree;
import com.haixiaoke.saas.org.service.IDeptService;
import com.haixiaoke.saas.system.controller.BaseController;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 部门Controller
 * 
 * @author panda
 * @date 2025-06-03
 */
@RestController
@RequestMapping("/manage/org/dept")
public class DeptController extends BaseController {
    @Autowired
    private IDeptService deptService;

    /**
     * 查询部门列表
     */
    @GetMapping("/list")
    public AjaxResult list(Dept dept) {
        List<Dept> list = deptService.selectDeptList(dept);
        return success(list);
    }

    /**
     * 查询部门列表
     */
    @GetMapping("/third-party/list")
    public AjaxResult thirdPartyList(Dept dept) {
        if (StrUtil.isBlank(dept.getPermissionChar())) {
            return error("权限字符不能为空");
        }
        Dept byPermissionChar = deptService.selectDeptByPermissionChar(dept.getPermissionChar());
        if (ObjectUtil.isEmpty(byPermissionChar)) {
            return error("权限字符数据异常");
        }
        dept.setAncestors(byPermissionChar.getDeptId().toString());
        dept.setPermissionChar(null);
        List<Dept> list = deptService.selectDeptList(dept);
        return success(list);
    }

    /**
     * 查询企业端部门管理数据结构
     */
    @GetMapping("/tree/list")
    public AjaxResult treeList(Dept dept) {
        List<DeptTree> list = deptService.buildTreeList(dept);
        return success(list);
    }


    /**
     * 查询企业端部门管理数据结构
     */
    @GetMapping("/third-party/tree/list")
    public AjaxResult thirdPartyTreeList(Dept dept) {
        if (StrUtil.isBlank(dept.getPermissionChar())) {
            return error("权限字符不能为空");
        }
        Dept byPermissionChar = deptService.selectDeptByPermissionChar(dept.getPermissionChar());
        if (ObjectUtil.isEmpty(byPermissionChar)) {
            return error("权限字符数据异常");
        }
        dept.setAncestors(byPermissionChar.getDeptId().toString());
        dept.setPermissionChar(null);
        List<DeptTree> list = deptService.buildTreeList(dept);
        return success(list);
    }

    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<Dept> depts = deptService.selectDeptList(null);
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 获取部门详细信息
     */
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable("deptId") Long deptId) {
        return success(deptService.selectDeptByDeptId(deptId));
    }

    /**
     * 新增部门
     */
    @Log(title = "部门", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Dept dept) {
        return deptService.insertDept(dept);
    }

    /**
     * 新增部门
     */
    @Log(title = "部门", businessType = BusinessType.INSERT)
    @PostMapping("/third-party")
    public AjaxResult thirdPartyAdd(@RequestBody Dept dept) {
        if (StrUtil.isBlank(dept.getPermissionChar())) {
            return error("权限字符不能为空");
        }
        Dept byPermissionChar = deptService.selectDeptByPermissionChar(dept.getPermissionChar());
        if (ObjectUtil.isEmpty(byPermissionChar)) {
            return error("权限字符数据异常");
        }
        if (dept.getParentId() != 0) {
            Dept byParentId = deptService.selectDeptByDeptId(dept.getParentId());
            if (!byParentId.getAncestors().contains("," + byPermissionChar.getDeptId()) &&
                    !Objects.equals(byParentId.getDeptId(), byPermissionChar.getDeptId())) {
                return error("父级部门不属于该平台");
            }
        }
        dept.setPermissionChar(null);
        return deptService.insertDept(dept);
    }

    /**
     * 修改部门
     */
    @Log(title = "部门", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Dept dept) {
        return deptService.updateDept(dept);
    }

    /**
     * 修改部门
     */
    @Log(title = "部门", businessType = BusinessType.UPDATE)
    @PutMapping("/third-party")
    public AjaxResult thirdPartyEdit(@RequestBody Dept dept) {
        if (StrUtil.isBlank(dept.getPermissionChar())) {
            return error("权限字符不能为空");
        }
        Dept byPermissionChar = deptService.selectDeptByPermissionChar(dept.getPermissionChar());
        if (ObjectUtil.isEmpty(byPermissionChar)) {
            return error("权限字符数据异常");
        }
        if (dept.getParentId() != 0) {
            Dept byParentId = deptService.selectDeptByDeptId(dept.getParentId());
            if (!byParentId.getAncestors().contains("," + byPermissionChar.getDeptId()) &&
                    !Objects.equals(byParentId.getDeptId(), byPermissionChar.getDeptId())) {
                return error("父级部门不属于该平台");
            }
        }
        dept.setPermissionChar(null);
        return deptService.updateDept(dept);
    }

    /**
     * 删除部门
     */
    @Log(title = "部门", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return warn("部门存在用户,不允许删除");
        }
        return toAjax(deptService.softDeleteDeptByDeptId(deptId));
    }
}
